package com.xhtt.fzxy.console.handler.post;


import com.xhtt.fzxy.console.Admin;
import com.xhtt.fzxy.console.AdminManager;
import com.xhtt.fzxy.console.handler.BaseHandler;

import net.lastcoder.ifserver.util.TextUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * auth: WenYF
 * date: 2018/5/5
 */
public class Login extends BaseHandler {
    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp, ProcessRetWrapper ret) throws IOException {
        String content = getData(req);
        if (TextUtils.isEmpty(content)) {
            ret.errcode = 2001;
            ret.errmsg = "参数错误";
            return;
        }
        
        // 判断类型
        String contentType = req.getContentType();

        String email, password;
        if (contentType.contains("form")) {
            // 表单
            content = URLDecoder.decode(content, req.getCharacterEncoding());
            Map<String, String> maps = formatQueryString(content);
            email = maps.get("email");
            password = maps.get("password");
        } else if (contentType.contains("json")) {
            // json
            JSONObject fromJson = new JSONObject(content);
            email = fromJson.getString("email");
            password = fromJson.getString("password");
        } else {
            ret.errcode = 2001;
            ret.errmsg = contentType + "不支持";
            return;
        }
        
        Admin admin = AdminManager.getInstance().login(req.getSession().getId()
                , email, password, req.getRemoteAddr());
        if (admin == null) {
            ret.errcode = 2001;
            ret.errmsg = "账号或密码错误";
            return;
        }

        req.getSession().setAttribute("channel", "fzxy");
        req.getSession().setAttribute("name", admin.name);
        req.getSession().setAttribute("level", admin.level);
        req.getSession().setAttribute("levelName", admin.levelName);
        req.getSession().setAttribute("loginTime", admin.currentLoginTime);

        JSONObject retJson = new JSONObject();
        retJson.put("name", admin.name);
        retJson.put("lastTime", admin.lastTimeLogin);
        
        ret.data = retJson;
//        ret.done = true;
//        loginSuccess(req, resp);
    }
    
//    public static void loginSuccess(HttpServletRequest req, HttpServletResponse resp) {
//        try {
////            req.getRequestDispatcher(req.getContextPath() + "/index.html").forward(req, resp);
//            resp.sendRedirect("../index.html");
//        }
//        catch (Exception e) {
//            Log.error(e.getMessage(), e);
//        }
//    }
}
